import React from 'react';
import {Input, Button, Select, Checkbox, Radio, Form, Col, InputNumber, TreeSelect, Icon, message, Upload} from 'antd'
import Utils from '../../utils/utils'
import {fetch, post} from '../../my_axios/api'

const {TextArea} = Input;
const FormItem = Form.Item;
const {Option, OptGroup} = Select;
const TreeNode = TreeSelect.TreeNode;

/**
 * 表单封装
 */
class BaseForm extends React.Component {
    state = {
        checked: false,
        reportCodeRule: {
            validateStatus: 'success',
            help: ''
        },
    };
    uploadField = '';
    currentField = '';
    currentType = '';
    currentDepartment = '';
    handleFormSubmit = () => {//提交（传递表单数据）
        var vm = this;
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (!err && vm.state.reportCodeRule.validateStatus === 'success') {
                let fieldsValue = this.props.form.getFieldsValue();//获取表单数据
                //调用父组件函数
                this.props.formSubmit(fieldsValue);
            }
        });

    };

    getTree(data) {
        if (data) {
            return data.map((item, index) => {
                if (item.children) {
                    return (
                        <TreeNode icon={<Icon type="home"/>} title={item.name} key={item.id} value={item.id}>
                            {this.getTree(item.children)}
                        </TreeNode>
                    )
                }
            })
        }
    }


    /**
     *关联查询
     * @param value
     */
    selectOnSearch = (type, field, value) => {
        if (value !== '') {
            this.props.getSearchData(value, type, field);
        } else {
            this.props.clearElement(this.currentField);//每次输入框为空清空列表
        }
    };

    /**
     * reportCode验证
     * @param e
     */
    codeOnBlur = (e) => {
        if (e.target.value !== '') {
            post('report/check_code', {code: e.target.value}).then(res => {
                if (res.status === 'success') {
                    let reportCodeRule = {};
                    if (res.data) {
                        reportCodeRule = {
                            validateStatus: 'success',
                            help: ''
                        }
                    } else {
                        console.log("已被使用");
                        reportCodeRule = {
                            validateStatus: 'error',
                            help: '编码已被使用'
                        };
                    }
                    this.setState({
                        reportCodeRule
                    })
                } else {
                    message.error(res.data.message);
                }
            }).catch(err => {
                console.log(err);
            })
        }
    }

    rest = () => {//重置
        this.props.form.resetFields();
    };

    normFile = (e) => {//上传附件验证（只允许上传SVG格式文件）
        if (e.fileList.length !== 0) {
            if (this.uploadField === 'svg') {
                if (e.fileList[e.fileList.length - 1].type !== 'image/svg+xml') {
                    message.error("只允许上传SVG文件")
                } else {
                    return [e.file];
                }
            } else if (this.uploadField === 'xls') {
                //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
                if (e.fileList[e.fileList.length - 1].name.split('.')[1] !== 'xls') {
                    message.error("只允许上传xls文件")
                } else {
                    return [e.file];
                }
            }
        } else {
            return [];
        }
    };

    getSeriesGroupOptions(data) {
        if (!data) {
            return [];
        } else {
            let options = [];
            data.map((item) => {
                options.push(<Option value={item.id} key={item.id}>{item.name}</Option>)
            });
            return options;
        }
    };

    //远程搜索
    getOptionList(data) {
        if (!data) {
            return [];
        } else {
            let strList = this.currentField.split('_');
            //修改时获取此组件类型
            let type_str=strList[0]+'_type';
            let options = [];
            data.map((item) => {
                options.push(<Option value={item.id} key={item.id}>{item.topic}</Option>)
            });
            if (this.props.form.getFieldValue(type_str) === 'CHART') {
                // console.log("测试："+this.props.form.getFieldValue('action_id'));
                let optGroupList = [];
                data.map((item) => {
                    optGroupList.push(
                        <OptGroup label={item.topic} key={item.id}>
                            {this.getSeriesGroupOptions(item.series_groups)}
                        </OptGroup>
                    )
                });
                return optGroupList;
            } else {
                return options;
            }
        }
    }

    onSelect = (field, value) => {
        this.currentField = field;
        this.currentType = value;
        this.props.clearElement(this.currentField);//每次选择，清空对应数据
    };
    treeSelectOnChange = (value) => {
        if (value !== undefined) {
            this.currentDepartment = value
        } else {
            this.currentDepartment = ''
        }
        if(this.props.getCurrentDepartmentId!==undefined){
            this.props.getCurrentDepartmentId(this.currentDepartment);//权限管理修改部门 清空下面选项
        }
    };
    checkContent=(rule,value,callback)=>{
        if(value===''){
            callback();
        }else if(!isNaN(value)){
            callback("不能为纯数字")
        }else{
            callback();
        }
    };
    initFormList = () => {
        const {getFieldDecorator} = this.props.form;
        let defaultColLayout = {
            xs: {span: 24},
            sm: {span: 24},
            md: {span: 12},
            lg: {span: 12},
            xl: {span: 12},
        };
        let defaultFormItemLayout = {
            labelCol: {
                xs: {span: 4},
                sm: {span: 4},
                md: {span: 8},
                lg: {span: 8},
                xl: {span: 8},
            },
            wrapperCol: {
                xs: {span: 20},
                sm: {span: 20},
                md: {span: 16},
                lg: {span: 16},
                xl: {span: 16},
            },
        };
        let textareaFormItemLayout = {
            labelCol: {
                xs: {span: 4},
                sm: {span: 4},
                md: {span: 4},
                lg: {span: 4},
                xl: {span: 4},
            },
            wrapperCol: {
                xs: {span: 20},
                sm: {span: 20},
                md: {span: 20},
                lg: {span: 20},
                xl: {span: 20},
            },
            // labelCol: {
            //     xs: {span: 2},
            //     sm: {span: 4},
            //     md: {span: 3},
            // },
            // wrapperCol: {
            //     xs: {span: 22},
            //     sm: {span: 20},
            //     md: {span: 21},
            // },
        };

        const formList = this.props.formList;
        let formItemList = [];
        if (formList && formList.length > 0) {
            formList.forEach((item) => {
                let label = item.label;
                let field = item.field;
                let initialValue = item.initialValue;
                let placeholder = item.placeholder;
                let width = item.width;
                let isDisabled = this.props.isDisabled
                let isRule = item.rule;
                if (item.colLayout) {
                    defaultColLayout = item.colLayout;
                }
                if (item.formItemLayout) {
                    defaultFormItemLayout = item.formItemLayout;
                } else {
                    if (item.type === 'TEXTAREA') {
                        defaultFormItemLayout = textareaFormItemLayout;
                    }
                }

                if (item.type === 'INPUT') {

                    const INPUT =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,
                                        rules: isRule ? [
                                            {required: true, message: '请输入' + label,},
                                            {
                                                validator:item.rules
                                            }
                                            ] : null,

                                    })(
                                        <Input placeholder={initialValue ? placeholder : ''} disabled={isDisabled}/>
                                    )
                                }
                            </FormItem>
                        </Col>
                    formItemList.push(INPUT);
                } else if (item.type === 'INPUTPASSWORD') {
                    const INPUTPASSWORD =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,
                                        rules: isRule ? [{required: true, message: '请输入' + label,}] : null,

                                    })(
                                        <Input type="password" placeholder={initialValue ? placeholder : ''}
                                               disabled={isDisabled}/>
                                    )
                                }
                            </FormItem>
                        </Col>
                    formItemList.push(INPUTPASSWORD);
                } else if (item.type === 'InputRuleCode') {//验证code是否可用
                    const InputRuleCode =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem
                                label={label} key={field} {...defaultFormItemLayout}
                                {...this.state.reportCodeRule}
                            >
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,
                                        rules: isRule ? [{required: true, message: '请输入' + label,}] : null,

                                    })(
                                        <Input onBlur={this.codeOnBlur} placeholder={initialValue ? placeholder : ''}
                                               disabled={isDisabled}/>
                                    )
                                }
                            </FormItem>
                        </Col>
                    formItemList.push(InputRuleCode);
                } else if (item.type === 'SELECT') {
                    const SELECT =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,
                                        rules: isRule ? [{required: true, message: '请选择' + label,}] : null,
                                    })(
                                        <Select
                                            showSearch
                                            disabled={isDisabled}
                                            placeholder={placeholder}
                                        >
                                            {Utils.getOptionList(item.list)}
                                        </Select>
                                    )
                                }
                            </FormItem>
                        </Col>;

                    formItemList.push(SELECT);
                } else if (item.type === 'relevantSelect') {
                    this.currentField=field;
                    const SELECT =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,
                                        rules: isRule ? [{required: true, message: '请选择' + label,}] : null,
                                    })(
                                        <Select
                                            disabled={isDisabled}
                                            onSelect={this.onSelect.bind(this, field)}//关联数据
                                            placeholder={placeholder}
                                        >
                                            {Utils.getOptionList(item.list)}
                                        </Select>
                                    )
                                }
                            </FormItem>
                        </Col>;

                    formItemList.push(SELECT);
                } else if (item.type === 'CHECKBOX') {
                    const CHECKBOX =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        valuePropName: 'checked',
                                        initialValue: initialValue,//true|false
                                    })(
                                        <Checkbox
                                            disabled={isDisabled}>
                                        </Checkbox>
                                    )
                                }
                            </FormItem>
                        </Col>;
                    formItemList.push(CHECKBOX);
                } else if (item.type === 'INPUTNUMBER') {
                    const INPUTNUMBER =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,//true|false
                                        rules: isRule ? [{required: true, message: '请输入' + label,}] : null,
                                    })(
                                        <InputNumber
                                            disabled={isDisabled}
                                            style={{width: '100%'}}
                                            min={0} max={9999}
                                        >
                                        </InputNumber>
                                    )
                                }
                            </FormItem>
                        </Col>;
                    formItemList.push(INPUTNUMBER);
                } else if (item.type === 'TREESELECT') {
                    const TREESELECT =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,
                                        rules: [{required: true, message: '请选择' + label, whitespace: true}],
                                    })(
                                        <TreeSelect
                                            onChange={this.treeSelectOnChange}
                                            disabled={isDisabled}
                                            // showSearch  是否可搜索
                                            style={{width: '100%'}}
                                            dropdownStyle={{maxHeight: 400, overflow: 'auto'}}
                                            placeholder="请选择部门"
                                            allowClear
                                        >
                                            <TreeNode icon={<Icon type="home"/>} title={this.props.addition.name}
                                                      value={this.props.addition.id} key="0-0">
                                                {this.getTree(this.props.addition.children)}
                                            </TreeNode>
                                        </TreeSelect>
                                    )
                                }
                            </FormItem>
                        </Col>;
                    formItemList.push(TREESELECT);
                } else if (item.type === 'TEXTAREA') {
                    const TEXTAREA =
                        <Col xs={24} sm={24} md={24} lg={24} xl={24} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,
                                        rules: isRule ? [{
                                            required: true,
                                            message: '请输入' + label,
                                            whitespace: true
                                        }] : null,

                                    })(
                                        <TextArea rows={item.rows ? item.rows : 3} placeholder={placeholder}
                                                  disabled={isDisabled}/>
                                    )
                                }
                            </FormItem>
                        </Col>
                    formItemList.push(TEXTAREA);
                }
                else if (item.type === 'SearchInput') {//远程搜索
                    const SearchInput =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}  {...defaultFormItemLayout}>
                                {
                                    getFieldDecorator(field, {
                                        initialValue: initialValue,
                                        rules: isRule ? [{
                                            required: true,
                                            message: '请选择' + label,
                                            whitespace: true
                                        }] : null,
                                    })(
                                        <Select
                                            showSearch
                                            onSearch={this.selectOnSearch.bind(this, this.currentType, field)}
                                            disabled={isDisabled}
                                            placeholder={placeholder}
                                            defaultActiveFirstOption={false}
                                            showArrow={false}
                                            filterOption={false}
                                        >
                                            {this.getOptionList(item.list)}
                                        </Select>
                                    )
                                }
                            </FormItem>
                        </Col>;
                    formItemList.push(SearchInput);
                } else if (item.type === 'UPLOAD') {
                    this.uploadField = item.uploadField;
                    const UPLOAD =
                        <Col {...defaultColLayout} key={field}>
                            <FormItem label={label} key={field}
                                      {...defaultFormItemLayout}
                            >
                                {
                                    getFieldDecorator(field, {
                                        valuePropName: 'fileList',
                                        getValueFromEvent: this.normFile,
                                        initialValue: initialValue,
                                        // rules: [{ type: "array", required: true, len: 1,message: '请选择'+label,}],
                                    })(
                                        <Upload {...this.props.uploadProps} >
                                            <Button>
                                                <Icon type="cloud-upload-o"/> 上传附件
                                            </Button>
                                        </Upload>
                                    )
                                }
                                {
                                    isDisabled ? <Button onClick={this.props.getSvgById}
                                                         style={{marginTop: 10}}>查看SVG</Button> : null
                                }

                            </FormItem>
                        </Col>;
                    formItemList.push(UPLOAD);
                }
                //如果不需要冒号：<FormItem label="~" colon={false}>
            })
        }
        return formItemList;
    };

    render() {
        return (
            <Form>
                {this.initFormList()}
            </Form>
        )
    }
};
export default Form.create({})(BaseForm);
